Make a device that I can play sounds with and if there is enough time make the led on the rp2040 react to the sounds that are played
import machine
import utime
from ws2812 import WS2812
# Define the pin connected to the LM4871 amplifier
signal_pin = machine.Pin(3)
shutdown_pin = machine.Pin(4, machine.Pin.OUT)
# Create a PWM object
pwm = machine.PWM(signal_pin)
shutdown_pin.low()
# Function to play a continuous tone at a given frequency, volume, and duty cycle
def play_tone(frequency, volume, duty_cycle, duration):
pwm.freq(int(frequency))
pwm.duty_u16(int(duty_cycle * volume))
utime.sleep_ms(duration)
pwm.duty_u16(0)
# LED Configuration
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
PURPLE = (80, 0, 80)
CYAN = (0, 255, 255)
WHITE = (255, 255, 255)
YELLOW = (255, 255, 0)
ORANGE = (255, 165, 0)
RED = (255, 0, 0)
COLORS = (BLACK, BLUE, PURPLE, CYAN, WHITE, YELLOW, ORANGE, RED)
led = WS2812(12, 1) # WS2812(pin_num, led_count)
# Note frequencies (Hz) for a custom melody
notes = {'C4': 261.63, 'D4': 293.66, 'E4': 329.63, 'F4': 349.23, 'G4': 392.00, 'A4': 440.00, 'B4': 493.88}
# Colors corresponding to each note
note_colors = {'C4': BLUE, 'D4': PURPLE, 'E4': CYAN,
'F4': WHITE, 'G4': YELLOW, 'A4': ORANGE, 'B4': RED}
# Custom melody with varied volume, speed, and mood
melody = [
('C4', 0.8, 100, 300), ('D4', 0.6, 80, 200), ('E4', 0.8, 100, 300), ('G4', 0.6, 80, 200),
('C4', 0.7, 90, 250), ('D4', 0.5, 70, 180), ('E4', 0.7, 90, 250), ('G4', 0.5, 70, 180),
('F4', 0.8, 100, 300), ('E4', 0.6, 80, 200), ('D4', 0.8, 100, 300), ('C4', 0.6, 80, 200),
('F4', 0.7, 90, 250), ('E4', 0.5, 70, 180), ('D4', 0.7, 90, 250), ('C4', 0.5, 70, 180),
('G4', 0.8, 100, 300), ('A4', 0.6, 80, 200), ('B4', 0.8, 100, 300), ('G4', 0.6, 80, 200),
('G4', 0.7, 90, 250), ('A4', 0.5, 70, 180), ('B4', 0.7, 90, 250), ('G4', 0.5, 70, 180)
]
# Repeat the melody
repeat_count = 3 # Adjust the number of repetitions as needed
for _ in range(repeat_count):
for note, volume, duty_cycle, duration in melody:
frequency = notes[note]
play_tone(frequency, volume, duty_cycle, duration)
led.pixels_fill(note_colors[note])
led.pixels_show()
utime.sleep_ms(duration)
led.pixels_fill(BLACK)
led.pixels_show()
# Add a small delay between repetitions
utime.sleep_ms(500)